﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using MangoCannon.Framework.Util;
using System.Reflection;

namespace MangoCannon.Framework.Base
{
    public class MangoContext
    {
        private MContext context;
        private MangoContext()
        {
        }

        public MangoContext(string jsonConfig){
            context = new MContext{ Apps = new Dictionary<string, IBaseApp>(),Nets = new Dictionary<string, IBaseNet>()};
            ContextConfig config = null;
            config = new JsonHelper().DeserializeJsonToObject<ContextConfig>(jsonConfig);
            Assembly ass = Assembly.Load(new AssemblyName(config.AssemblyName));
            Logger.getLogger().writeLog(this, "Loading Context:"+config.AssemblyName+"...");
            //Read All Application
            foreach (var appName in config.ApplicationNames)
            {
                Type type = ass.GetType(config.NameSpaceName+"." + appName);
                Object obj = Activator.CreateInstance(type);
                context.Apps.Add(appName,(IBaseApp)obj);
            }
            //Setting
            context.Config = config;
            IBaseApp[] apps = new IBaseApp[context.Apps.Count];
            context.Apps.Values.CopyTo(apps,0);
            context.MangoFramework = new FrameworkService(apps,context.Config);
        }


        public MContext getContext(){
            return context;
        }
    }

    public class MContext
    {
        public Dictionary<string,IBaseApp> Apps
        {
            get;set;
        }
        public Dictionary<string, IBaseNet> Nets
        {
            get;set;
        }
        public ContextConfig Config
        {
            get;set;
        }

        public IFramework MangoFramework
        {
            get;set;
        }

        public void luanchFramework(){
            if (Config.ShowLog)
            {
                Logger.getLogger().writeLog(this, "Luanching Mango...");
            }
            MangoFramework.luanch();
        }

        public void shutdownFramework()
        {
            MangoFramework.shutdown();
        }
    }
}
